#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: twl
@date: 2022/5/9 11:03
@description:
"""
import logging
from logging.handlers import RotatingFileHandler

import colorlog

from common.boot_args import config_name, log_file, log_level
from config import profiles


class LoggerHandler(logging.Logger):

    def __init__(
        self,
        name="root",
        level="DEBUG",
        file=None,
        format="%(asctime)s - %(threadName)s - %(filename)s - %(lineno)d - %(name)s - %(levelname)s - %(message)s"):
    
        # logger(name) 直接超继承logger当中的name
        super().__init__(name)
    
        # 设置收集器级别
        # logger.setLevel(level)
        self.setLevel(level)  # 继承了Logger 返回的实例就是自己
    
        # 初始化format，设置格式
        file_format = logging.Formatter(format)
        # 初始化处理器
        # 如果file为空，就执行stream_handler,如果有，两个都执行
        final_log_file = log_file if log_file is not None else profiles.app_config[
            config_name].LOG_FILE
        final_log_level = LoggerHandler.get_final_log_level(
            log_level) if log_level is not None else profiles.app_config[config_name].LOG_LEVEL
        if final_log_file:
            file_handler = RotatingFileHandler(
			final_log_file,
			maxBytes=1024 * 1024 * 100,
			backupCount=10)
            # 设置handler级别
            file_handler.setLevel(final_log_level)
            # 添加handler
            self.addHandler(file_handler)
            # 添加日志处理器
            file_handler.setFormatter(file_format)

        log_colors_config = {
            'DEBUG': 'white',
            'INFO': 'green',
            'WARNING': 'yellow',
            'ERROR': 'red',
            'CRITICAL': 'bold_red',
        }
        console_formatter = colorlog.ColoredFormatter(
            fmt='%(log_color)s' + format,
            log_colors=log_colors_config)
        stream_handler = logging.StreamHandler()
        stream_handler.setLevel(final_log_level)
        stream_handler.setFormatter(console_formatter)
        self.addHandler(stream_handler)



    @staticmethod
    def get_final_log_level(input_log_level):
        if 'info' == input_log_level or 'INFO' == input_log_level:
            return logging.INFO
        elif 'debug' == input_log_level or 'DEBUG' == input_log_level:
            return logging.DEBUG
        elif 'error' == input_log_level or 'ERROR' == input_log_level:
            return logging.ERROR
        else:
            return logging.INFO
# 为了确保每次是同一个文件，调用同样的logger对象(防止手误写错文件名字),所以在这里直接初始化logger这个对象比较好
# 可以将name,file参数写入配置文件中（这里我是直接写到了配置文件当中，也可以直接传）
# logger = LoggerHandler('tt',logging.INFO,'/Users/bijiahao/log/logs/log.log')
# logger = LoggerHandler("python21",file="demo.txt")


if __name__ == '__main__':
    logger = LoggerHandler()
    logger.info("world")
    # 继承后---测试.py:44:root:DEBUG:world

